using System;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace ClownFish
{
	public static class SqlServerHelper
	{
		private static Regex regex_0 = new Regex("^\\s*GO\\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline);

		public static void ExecuteTsqlScript(SqlConnection connection, string SqlText, Action<string> execNotify)
		{
			if (string.IsNullOrEmpty(SqlText))
			{
				return;
			}
			if (connection == null)
			{
				throw new ArgumentNullException("connection");
			}
			string[] array = SqlServerHelper.regex_0.Split(SqlText);
			bool flag = false;
			try
			{
				if (connection.State != ConnectionState.Open)
				{
					connection.Open();
					flag = true;
				}
				SqlCommand sqlCommand = connection.CreateCommand();
				sqlCommand.CommandType = CommandType.Text;
				sqlCommand.CommandTimeout = 0;
				string[] array2 = array;
				for (int i = 0; i < array2.Length; i++)
				{
					string text = array2[i];
					string text2 = text.Trim();
					if (text2.Length > 0)
					{
						sqlCommand.CommandText = text2;
						if (execNotify != null)
						{
							execNotify(text2);
						}
						sqlCommand.ExecuteNonQuery();
					}
				}
			}
			finally
			{
				if (flag)
				{
					connection.Close();
				}
			}
		}
	}
}
